import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {IConfig} from '../service/config.interface';
import {ElectronHttpClient} from '../core/httpclient/electron-http-client.service';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ConsulRepository {
  constructor(private httpClient: ElectronHttpClient) {
  }

  public getService(config: IConfig) {
    const url = `http://${config.host}:${config.port}/v1/agent/services`;
    return this.httpClient.get(url).pipe(
      map(resp => resp.data)
    );
  }

  public deregister(serviceId: string, config: IConfig): Observable<boolean> {
    const url = `http://${config.host}:${config.port}/v1/agent/service/deregister/${serviceId}`;
    return this.httpClient.put(url).pipe(
      map(() => true)
    );
  }

  public healthCheck(address: string): Observable<any> {
    const url = `http://${address}/actuator/health`;
    return this.httpClient.get(url).pipe(
      map(resp => resp.data)
    );
  }
}
